package com.wdb007.venus.wss.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.channelgroup.BookCaseChannelGroups;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;

@Service("bookCaseCheckResService")
public class BookCaseCheckResService implements WebSocketServerService {
	private static Logger logger = LoggerFactory.getLogger(BookCaseCheckResService.class);
	
	@Autowired
	private BookgridService bookgridService;
	@Autowired
	private ProcessInstructionService processInstructionService; 
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		JSONObject jsonObj = JSON.parseObject(request);
		try {
			
			String bookcaseId = BookCaseChannelGroups.getBookCaseId(ctx.channel());
			int dataCount = 0 ;
			try {
				JSONArray datas = jsonObj.getJSONArray("data");
				for(int i=0;i<datas.size();i++) {
					JSONObject data = (JSONObject) datas.get(i);
					dataCount += data.getJSONArray(bookcaseId +"0"+ (i+1)).size();
					logger.info("书格{},数量{}",bookcaseId +"0"+ (i+1), data.getJSONArray(bookcaseId +"0"+ (i+1)).size());
				}
			}catch (Exception e) {
				logger.info(e.getMessage());
			}
			String pushId = jsonObj.getString("pushId");
			ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookcaseId);
			pi.setInstructionGroupId(Long.valueOf(pushId));
			pi.setStockCount(dataCount);
			processInstructionService.bookCaseCheckRes(pi);
			
			jsonObj.put("bookshelf_code", bookcaseId);
			logger.info("debug {}: 书柜{}, data数量{},响应内容{}", jsonObj.getString("action"), bookcaseId, dataCount,jsonObj.toJSONString());
			bookgridService.bookCaseCheck(jsonObj);
		} catch (Exception e) {
			logger.error("整书柜图书盘点异常", e);
		}
		return null;
	}

}
